import remove from 'lodash/remove';
import findIndex from 'lodash/findIndex';
export const generateToast=({
    log,
    show,
    hide,
    update,
    ignore,
}={})=>{
    let showCount=1;
    let toasts=[];
    // let currentId=0;

    const getUpdateArgs=()=>{
        const {args,id}=toasts[toasts.length-1];
/*        if(currentId==id){
            return null;
        }*/
        const _mask=findIndex(toasts,item=>item.mask)>-1;
        const opt={
            ...args,
            mask:_mask,
            duration:24*60*60*1000//忽略自动关闭功能
        };
        // currentId=id;
        return opt;
    };

    let willShowHandle=null;
    const _hide=function(id){
        if(!id){
            console.warn('未提供参数id，请使用toast.show().hide()关闭toast或使用toast.hide(id)');
        }
        log&&log('toast._hide..');
        remove(toasts,item=>item.id==id);
        if(toasts.length>0){
            const args=getUpdateArgs();
            if(!args){
                return;
            }
            update(args);
            return;
        }
        //ignore时间内，并未真正show
        if(ignore&&willShowHandle){
            clearTimeout(willShowHandle);
            willShowHandle=null;
            return;
        }
        hide();
    };

    const _show = function(args={}){
        const id=showCount++;
        log&&log('toast._show..');
        const {duration=0,mask,..._args}=args;
        toasts.push({
            id,
            args:_args,
            duration,
            mask:!!mask
        });

        if(duration){
            setTimeout(function(){
                _hide(id);
            },duration);
        }

        const opt=getUpdateArgs();
        if(toasts.length==1){
            if(ignore&&!willShowHandle){
                willShowHandle=setTimeout(()=>{
                    willShowHandle=null;
                    show(opt);
                },ignore);
            }
            if(!ignore){
                show(opt);
            }
        }else{
            update(opt);
        }
        return {
            id,
            hide(){
                _hide(id);
            },
            update(opt){
                _update(id,opt);
            }
        }
    };

    //更新时duration和mask无效
    const _update=function(id,{
        mask,
        duration,
        ...args
    }={}){
        if(!id){
            console.warn('未提供参数id');
        }
        log&&log('toast._update..');
        const index=findIndex(toasts,item=>item.id==id);
        let opt;
        if(index>-1&&(opt=toasts[index])){
            opt.args={
                ...opt.args,
                ...args
            };
        }
        const topArgs=getUpdateArgs();
        if(!topArgs){
            return;
        }
        update(topArgs);
    };
    const hideAll=function(){
        toasts=[];
        hide();
    };
    return {
        show:_show,
        hide:_hide,
        update:_update,
        hideAll
    }
};
export const genToast=generateToast;
export default generateToast;